// src/services/broadcasts.js - 全球广播服务

import { get, post, put, del } from './api';
import {
  getAllBroadcasts as localGetAllBroadcasts,
  createBroadcast as localCreateBroadcast,
  initBroadcasts
} from '../utils/localStorage';

/**
 * 初始化广播数据
 */
export const initBroadcastsData = () => {
  initBroadcasts();
};

/**
 * 获取全球广播列表（使用Broadcasts API）
 * @param {Object} params - 查询参数
 * @returns {Promise} - 广播列表
 */
export const getBroadcasts = async (params = {}) => {
  try {
    const response = await get('/broadcasts/all');

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      const broadcasts = response.data.broadcasts || [];

      // 适配数据格式，将BroadcastInfo转换为前端期望的格式
      const adaptedBroadcasts = broadcasts.map(broadcast => ({
        id: broadcast.broadcastId,
        title: broadcast.title,
        content: broadcast.content,
        type: broadcast.category, // 将category映射为type
        category: broadcast.category,
        author: broadcast.author,
        authorLevel: broadcast.authorLevel,
        authorTitle: broadcast.authorTitle,
        username: broadcast.author, // 兼容字段
        createTime: new Date().toISOString(), // 后端没有返回时间，使用当前时间
        updateTime: new Date().toISOString(),
        likes: broadcast.likes,
        downloads: broadcast.downloads,
        views: broadcast.views,
        tags: broadcast.tags ? (typeof broadcast.tags === 'string' ? broadcast.tags.split(',') : broadcast.tags) : [],
        resourceLink: broadcast.resourceUrl || null,
        resourceUrl: broadcast.resourceUrl || null,
        hasResource: broadcast.hasResource,
        resourceType: broadcast.resourceType,
        resourceSize: broadcast.resourceSize,
        isLiked: broadcast.isLiked,
        isHot: broadcast.isHot,
        isPinned: false,
        exposure: 0,
        urgency: 'normal'
      }));

      return {
        success: true,
        data: {
          broadcasts: adaptedBroadcasts,
          pagination: {
            total: adaptedBroadcasts.length,
            page: 1,
            limit: adaptedBroadcasts.length,
            pages: 1
          },
          statistics: {
            totalBroadcasts: adaptedBroadcasts.length,
            todayBroadcasts: 0,
            totalReads: adaptedBroadcasts.reduce((sum, b) => sum + (b.views || 0), 0)
          }
        }
      };
    } else {
      throw new Error(response.message || '获取广播列表失败');
    }
  } catch (error) {
    console.warn('获取广播列表失败，使用本地数据:', error);
    // 回退到本地存储
    const broadcasts = localGetAllBroadcasts();

    // 应用过滤和分页
    let filteredBroadcasts = broadcasts;

    if (params.type) {
      filteredBroadcasts = filteredBroadcasts.filter(b => b.type === params.type);
    }

    const page = parseInt(params.page) || 1;
    const limit = parseInt(params.limit) || 20;
    const startIndex = (page - 1) * limit;
    const endIndex = startIndex + limit;

    const paginatedBroadcasts = filteredBroadcasts.slice(startIndex, endIndex);

    return {
      success: true,
      data: {
        broadcasts: paginatedBroadcasts.map(broadcast => ({
          id: broadcast.id,
          title: broadcast.title,
          content: broadcast.content,
          type: broadcast.type,
          category: broadcast.type,
          author: broadcast.author,
          authorLevel: broadcast.authorLevel,
          authorTitle: broadcast.authorTitle,
          username: broadcast.author,
          createTime: broadcast.createTime,
          updateTime: broadcast.createTime,
          likes: broadcast.likes || 0,
          downloads: broadcast.downloads || 0,
          views: broadcast.views || 0,
          tags: broadcast.tags || [],
          resourceLink: broadcast.resourceLink,
          resourceUrl: broadcast.resourceLink,
          hasResource: !!broadcast.resourceLink,
          resourceType: broadcast.resourceType || 'torrent',
          resourceSize: broadcast.size,
          isLiked: false,
          isHot: (broadcast.views || 0) >= 300,
          isPinned: false,
          exposure: broadcast.exposure || 0,
          urgency: broadcast.urgency || 'normal'
        })),
        pagination: {
          total: filteredBroadcasts.length,
          page: page,
          limit: limit,
          pages: Math.ceil(filteredBroadcasts.length / limit)
        },
        statistics: {
          totalBroadcasts: broadcasts.length,
          todayBroadcasts: broadcasts.filter(b => {
            const today = new Date().toDateString();
            const createDate = new Date(b.createTime).toDateString();
            return createDate === today;
          }).length,
          totalReads: broadcasts.reduce((sum, b) => sum + (b.views || 0), 0)
        }
      }
    };
  }
};

/**
 * 获取广播详情
 * @param {string|number} broadcastId - 广播ID
 * @returns {Promise} - 广播详情
 */
export const getBroadcastDetail = async (broadcastId) => {
  try {
    const response = await get(`/broadcasts/${broadcastId}`);

    // 适配后端响应格式
    if (response.code === 200) {
      const broadcast = response.data;

      // 适配数据格式
      const adaptedBroadcast = {
        id: broadcast.broadcastId,
        broadcastId: broadcast.broadcastId,
        title: broadcast.title,
        content: broadcast.content,
        type: broadcast.category,
        category: broadcast.category,
        author: broadcast.author,
        authorLevel: broadcast.authorLevel,
        authorTitle: broadcast.authorTitle,
        username: broadcast.author,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        likes: broadcast.likes,
        downloads: broadcast.downloads,
        views: broadcast.views,
        tags: broadcast.tags ? (typeof broadcast.tags === 'string' ? broadcast.tags.split(',') : broadcast.tags) : [],
        hasResource: broadcast.hasResource,
        resourceType: broadcast.resourceType,
        resourceSize: broadcast.resourceSize,
        isLiked: broadcast.isLiked,
        isHot: broadcast.isHot
      };

      return {
        success: true,
        data: {
          broadcast: adaptedBroadcast
        }
      };
    } else {
      throw new Error(response.message || '获取广播详情失败');
    }
  } catch (error) {
    console.warn('获取广播详情失败，使用本地数据:', error);
    // 回退到本地存储
    const broadcasts = localGetAllBroadcasts();
    const broadcast = broadcasts.find(b => b.id.toString() === broadcastId.toString());

    if (!broadcast) {
      return {
        success: false,
        message: '广播不存在'
      };
    }

    return {
      success: true,
      data: {
        broadcast: {
          id: broadcast.id,
          broadcastId: broadcast.id,
          title: broadcast.title,
          content: broadcast.content,
          type: broadcast.type,
          category: broadcast.type,
          author: broadcast.author,
          authorLevel: broadcast.authorLevel,
          authorTitle: broadcast.authorTitle,
          username: broadcast.author,
          createTime: broadcast.createTime,
          updateTime: broadcast.createTime,
          likes: broadcast.likes || 0,
          downloads: broadcast.downloads || 0,
          views: (broadcast.views || 0) + 1, // 增加阅读数
          tags: broadcast.tags || [],
          hasResource: !!broadcast.resourceLink,
          resourceType: broadcast.resourceType || 'torrent',
          resourceSize: broadcast.size,
          isLiked: false,
          isHot: (broadcast.views || 0) >= 300
        }
      }
    };
  }
};

/**
 * 创建广播
 * @param {Object} broadcastData - 广播数据
 * @returns {Promise} - 创建结果
 */
export const createBroadcast = async (broadcastData) => {
  try {
    // 适配后端期望的字段格式
    const payload = {
      title: broadcastData.title,
      content: broadcastData.content,
      category: broadcastData.type || broadcastData.category, // 使用type或category
      resourceUrl: broadcastData.resourceUrl || broadcastData.resourceLink || null,
      tags: Array.isArray(broadcastData.tags) ? broadcastData.tags.join(',') : (broadcastData.tags || '')
    };

    const response = await post('/broadcasts/create', payload);

    // 适配后端响应格式
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: '广播发布成功'
      };
    } else {
      throw new Error(response.message || '创建广播失败');
    }
  } catch (error) {
    console.warn('创建广播失败，使用本地存储:', error);
    // 回退到本地存储
    const result = localCreateBroadcast(broadcastData);
    return result;
  }
};

/**
 * 删除广播（注意：后端没有删除接口，这里仅为API兼容性保留）
 * @param {string|number} broadcastId - 广播ID
 * @returns {Promise} - 删除结果
 */
export const deleteBroadcast = async (broadcastId) => {
  console.warn('后端不支持删除广播接口');
  return {
    success: false,
    message: '后端不支持删除广播功能'
  };
};

/**
 * 点赞广播
 * @param {string|number} broadcastId - 广播ID
 * @returns {Promise} - 点赞结果
 */
export const likeBroadcast = async (broadcastId) => {
  try {
    const response = await post(`/broadcasts/${broadcastId}/like`);

    // 适配后端响应格式
    if (response.code === 200) {
      return {
        success: true,
        data: {
          liked: response.data.liked,
          totalLikes: response.data.totalLikes
        }
      };
    } else {
      throw new Error(response.message || '点赞失败');
    }
  } catch (error) {
    console.warn('点赞广播失败，使用本地存储:', error);
    // 本地存储简化实现
    const broadcasts = localGetAllBroadcasts();
    const broadcastIndex = broadcasts.findIndex(b => b.id.toString() === broadcastId.toString());

    if (broadcastIndex === -1) {
      return {
        success: false,
        message: '广播不存在'
      };
    }

    broadcasts[broadcastIndex].likes = (broadcasts[broadcastIndex].likes || 0) + 1;
    localStorage.setItem('starrypt_broadcasts', JSON.stringify(broadcasts));

    return {
      success: true,
      data: {
        liked: true,
        totalLikes: broadcasts[broadcastIndex].likes
      }
    };
  }
};

/**
 * 搜索广播
 * @param {Object} params - 搜索参数
 * @returns {Promise} - 搜索结果
 */
export const searchBroadcasts = async (params = {}) => {
  try {
    const query = new URLSearchParams();
    if (params.query) query.append('query', params.query);
    if (params.category) query.append('category', params.category);
    if (params.hasResource !== undefined) query.append('hasResource', params.hasResource);

    // 将tags参数转换为query参数（后端搜索支持在tags字段中搜索）
    if (params.tags && !params.query) {
      query.append('query', params.tags);
    }

    const queryString = query.toString();
    const endpoint = queryString ? `/broadcasts/search?${queryString}` : '/broadcasts/search';

    const response = await get(endpoint);

    // 适配后端响应格式
    if (response.code === 200) {
      const broadcasts = response.data.broadcasts || [];

      // 适配数据格式
      const adaptedBroadcasts = broadcasts.map(broadcast => ({
        id: broadcast.broadcastId,
        title: broadcast.title,
        content: broadcast.content,
        type: broadcast.category,
        category: broadcast.category,
        author: broadcast.author,
        authorLevel: broadcast.authorLevel,
        authorTitle: broadcast.authorTitle,
        username: broadcast.author,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        likes: broadcast.likes,
        downloads: broadcast.downloads,
        views: broadcast.views,
        tags: broadcast.tags ? (typeof broadcast.tags === 'string' ? broadcast.tags.split(',') : broadcast.tags) : [],
        hasResource: broadcast.hasResource,
        resourceType: broadcast.resourceType,
        resourceSize: broadcast.resourceSize,
        isLiked: broadcast.isLiked,
        isHot: broadcast.isHot
      }));

      return {
        success: true,
        data: {
          broadcasts: adaptedBroadcasts,
          pagination: {
            total: adaptedBroadcasts.length,
            page: 1,
            limit: adaptedBroadcasts.length,
            pages: 1
          },
          searchQuery: params.query || params.tags,
          filters: {
            category: params.category,
            hasResource: params.hasResource
          }
        }
      };
    } else {
      throw new Error(response.message || '搜索失败');
    }
  } catch (error) {
    console.warn('搜索广播失败，使用本地数据:', error);
    // 回退到本地存储
    const broadcasts = localGetAllBroadcasts();

    let filteredBroadcasts = broadcasts;

    // 应用搜索过滤
    if (params.query) {
      const searchQuery = params.query.toLowerCase();
      filteredBroadcasts = filteredBroadcasts.filter(broadcast =>
        broadcast.title.toLowerCase().includes(searchQuery) ||
        broadcast.content.toLowerCase().includes(searchQuery) ||
        (broadcast.tags && broadcast.tags.some(tag => tag.toLowerCase().includes(searchQuery)))
      );
    }

    if (params.category) {
      filteredBroadcasts = filteredBroadcasts.filter(b => b.type === params.category);
    }

    if (params.hasResource !== undefined) {
      filteredBroadcasts = filteredBroadcasts.filter(b =>
        params.hasResource ? !!b.resourceLink : !b.resourceLink
      );
    }

    return {
      success: true,
      data: {
        broadcasts: filteredBroadcasts.map(broadcast => ({
          id: broadcast.id,
          title: broadcast.title,
          content: broadcast.content,
          type: broadcast.type,
          category: broadcast.type,
          author: broadcast.author,
          username: broadcast.author,
          createTime: broadcast.createTime,
          likes: broadcast.likes || 0,
          views: broadcast.views || 0,
          hasResource: !!broadcast.resourceLink,
          tags: broadcast.tags || []
        })),
        pagination: {
          total: filteredBroadcasts.length,
          page: 1,
          limit: filteredBroadcasts.length,
          pages: 1
        },
        searchQuery: params.query,
        filters: {
          category: params.category,
          hasResource: params.hasResource
        }
      }
    };
  }
};

export default {
  initBroadcastsData,
  getBroadcasts,
  getBroadcastDetail,
  createBroadcast,
  deleteBroadcast,
  likeBroadcast,
  searchBroadcasts
}; 